import Axios from 'axios'
import Qs from 'qs'
import { Message } from "element-ui" 
import consts from './consts.js'

function getToken(){ 
    return sessionStorage[consts.AuthKey.ADMIN]
}

const axios = Axios.create();

const isProduction = process.env.NODE_ENV === 'production'

axios.defaults.timeout = 15000;
axios.defaults.baseURL = isProduction ? process.env.VUE_APP_BASEURL : '/';
axios.defaults.headers = { 'X-Requested-With': 'XMLHttpRequest' }

axios.defaults.paramsSerializer = function (params) {
    return Qs.stringify(params)
}
// http request 拦截器
axios.interceptors.request.use(
    config => {
        //Authorization
        let auth = getToken()
        if (auth) {
            config.headers.Authorization = auth;
        }
        return config;
    },
    err => {
        return Promise.reject({ msg: err, statusCode: -1 });
    });

axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        console.log("response error!")
        console.log(error)
        if (error.response) {
            switch (error.response.status) {
                case 400:
                    Message({ message: `[${error.response.status}] 请求参数有误`, type: "error" })
                    break;
                case 401:
                    Message({ message: `当前页面权限资源不足，请联系管理员开通相关权限。`, type: "error" })
                    break;
                case 404:
                    Message({ message: `[${error.response.status}] 请求的接口不存在`, type: "error" })
                    break;
                case 500:
                    Message({ message: `[${error.response.status}] 服务端错误`, type: "error" })
                    break;
                case 504:
                    Message({ message: `[${error.response.status}] 服务端错误`, type: "error" })
                    break;
                default:
                    Message({ message: `[${error.response.status}] 请求发生错误,请稍候重试`, type: "error" })
                    break;
            }
            return Promise.reject({ msg: error, statusCode: error.response.status })
        } else {
            Message({ message: `请求发生错误,请稍候重试`, type: "error" })
        }
        return Promise.reject({ msg: error, statusCode: 0 })
    }
);


export default axios;
